#include <Reg51.h>
#include "LCD1602.h"
#include "delay.h"
#include "DS18B20.h"
#include "ds1302.h"
#include "menu.h"
#include "Key.h"
#include "show.h"
#include "set.h"
#include "Buzzer.h"

unsigned char Key, SetFinish,alarmring = 0;
unsigned char mode, add, TimeChoice, AlarmFlag;
unsigned char year, month, day, week, hour, min, sec, temperture;
unsigned char code AlarmSwitchStr[] = "Alarm: OFF";
unsigned char AlarmTime[2] = { 0x00,0x00 };

void Timer0Init(void);
void AlarmCompare(void);
void calendar_save_set_time(void);
void Timer1Init(void);



void main()
{
	
	LCDInit();
	ds1302_init();
	ds18b20_init();
	Timer0Init();
	DelayXms(20);
	while(1)
	{
		Key = key_scan(0);
		if(1 == Key)//模式设置
		{
			mode++;
			if(3 == mode)
				mode = 0;
			SetFinish = 0;
			TimeChoice = 0;
			if(mode == 2)
			{
				LCDWriteCmd(0x01);//清屏	
			}
			Buzzer_Time(100);	
		}				
		else if(2 == Key)//进入设置模式时，对应位选择设置
		{
			TimeChoice++;
			TimeChoice %= 7;//越界清零
			Buzzer_Time(100);
		}
		else if(3 == Key)//进入设置模式时，进行数据加操作
		{
			add = 1;
			Buzzer_Time(100);
		}	
		else if(4 == Key)//设置完成，恢复正常显示模式
		{
			SetFinish = 1;
			TimeChoice = 0;
			mode = 0;
			calendar_save_set_time();
			Buzzer_Time(100);			
		}
		CursorFlashing();
		TimeSet();
		AlarmSet();	
		TimeShow();
		AlarmCompare();
	}
}

void Timer0Init(void)		//1毫秒@11.0592MHz
{
	TMOD &= 0xF0;		//设置定时器模式
	TMOD |= 0x01;		//设置定时器模式
	TL0 = 0x66;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	ET0 = 1;
	EA = 1;
	TR0 = 1;		//定时器0开始计时
}

void timer0_ISR() interrupt 1
{
	static unsigned char timer0Cnt = 0;
	static unsigned char oneflag = 1;
	TR0 = 0;
	timer0Cnt++;
	if (timer0Cnt >= 50)
	{
		timer0Cnt = 0;
		if(0 == mode)
			ds1302_read_time();			
		if(oneflag == 1)
		{
			oneflag = 0;
			AlarmTime[0] = min;
			AlarmTime[1] = hour;//记录初始闹钟时间		
		}
		temperture = ds18b20_read_temperture();
	}
	TL0 = 0x66;		//设置定时初值
	TH0 = 0xFC;		//设置定时初值
	TR0 = 1;
}

void AlarmCompare(void)
{
	unsigned char i;
	if(AlarmFlag && SetFinish)
	{
		if(AlarmTime[1] == hour)
		{
			if(AlarmTime[0] == min)//对比闹钟设置时间和当前时间，相同则闹铃
				{
					for(i = 0; i < 60000; i++)
					{
						BEEP = ~BEEP;
						if((KEY1==0||KEY2==0||KEY3==0||KEY4==0))//任意按键按下
						{
							DelayXms(10);
							if(KEY1==0||KEY2==0||KEY3==0||KEY4==0)
							{
								break;
							}
							
						}
					}
//					alarmring = 0;
						
					
				}
		}	
						
	}	
}

void calendar_save_set_time(void)
{
	DS1302_TIME[0] = sec;
	DS1302_TIME[1] = min;
	DS1302_TIME[2] = hour;
	DS1302_TIME[3] = day;
	DS1302_TIME[4] = month;
	DS1302_TIME[5] = week;
	DS1302_TIME[6] = year;
	ds1302_init();		
}	
